package com.zhengwenze.springbootdemo.controller;


import com.google.gson.Gson;
import com.zhengwenze.springbootdemo.util.MyUtil;
import okhttp3.HttpUrl;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.InputStream;

@RestController
@CrossOrigin({"http://localhost:8080"})
public class ImageController {

    public static final String hostUrl = "https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti";
    public static final String appid = "913b9b0c"; //这里填写APPID
    public static final String apiSecret = "MmY5Y2U2ZGQyNTUzNjliZTVhMmUxNGFh"; //这里填写Secret
    public static final String apiKey = "07d2b7af0057980bdaf534508d82c7c2"; //这里填写Key
    public static final Gson gson = new Gson();
    String outputPath;

    @PostMapping("/image")
    public String image(@RequestBody ImageRequest request) throws Exception {
        System.out.println("Received request body: " + gson.toJson(request));

        String content = request.getContent();
        String fileName = request.getFileName();

        if (content == null || fileName == null) {
            throw new IllegalArgumentException("Missing required parameters: content or fileName");
        }

        String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
        String json = "{\n" + "  \"header\": {\n" + "    \"app_id\": \"" + appid + "\",\n" + "    \"uid\": \"" + UUID.randomUUID().toString().substring(0, 15) + "\"\n" + "  },\n" + "  \"parameter\": {\n" + "    \"chat\": {\n" + "      \"domain\": \"s291394db\",\n" + "      \"temperature\": 0.5,\n" + "      \"max_tokens\": 4096,\n" + "      \"width\": 1024,\n" + "      \"height\": 1024\n" + "    }\n" + "  },\n" + "  \"payload\": {\n" + "    \"message\": {\n" + "      \"text\": [\n" + "        {\n" + "          \"role\": \"user\",\n" + "          \"content\": \"" + content + "\"\n" + "        }\n" + "      ]\n" + "    }\n" + "  }\n" + "}";
        String res = MyUtil.doPostJson(authUrl, null, json);
        System.out.println(res);
        JsonParse jsonParse = gson.fromJson(res, JsonParse.class);
        byte[] imageBytes = Base64.getDecoder().decode(jsonParse.payload.choices.text.get(0).content);
        outputPath = "src/main/resources/static/" + fileName + ".png";
        try (FileOutputStream imageOutFile = new FileOutputStream(outputPath)) {
            imageOutFile.write(imageBytes);
            System.out.println("图片已成功保存到: " + outputPath);
        } catch (IOException e) {
            System.err.println("保存图片时出错: " + e.getMessage());
        }
        return new ImageResponse("图片生成成功! ", outputPath).info();
    }
    @GetMapping("/image")
    public ResponseEntity<byte[]> getImage() throws IOException {
        String path = outputPath;
        // 加载图片资源
        Resource resource = new ClassPathResource(path);
        InputStream inputStream = resource.getInputStream();
        byte[] imageBytes = inputStream.readAllBytes();
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        // 返回图片字节数组
        return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
    }
    // 鉴权方法保持不变
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "POST " + url.getPath() + " HTTP/1.1";
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).addQueryParameter("date", date).addQueryParameter("host", url.getHost()).build();
        return httpUrl.toString();
    }
}
class JsonParse {
    Payload payload;
}
class Payload {
    Choices choices;
}
class Choices {
    List<Text> text;
}
class Text {
    String content;
}

class ImageRequest {
    private String content;
    private String fileName;
    // getters and setters
    public String getContent() { return content; }
    public void setContent(String content) {
        this.content = content;
    }
    public String getFileName() { return fileName; }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

class ImageResponse {
    private final String message;

    public String getMessage() {
        return message;
    }

    public String getImagePath() {
        return imagePath;
    }

    private final String imagePath;
    public ImageResponse(String message, String imagePath) {
        this.message = message;
        this.imagePath = imagePath;
    }
    public String info() {
        return message + imagePath;
    }
}